package cn.stylefeng.guns.modular.system.orgdata.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.convert.Convert;
import cn.hutool.core.util.ArrayUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import cn.stylefeng.guns.modular.base.userorgdata.mapper.UserOrgDataMapper;
import cn.stylefeng.guns.modular.system.orgdata.constants.OrgDataConstants;
import cn.stylefeng.guns.modular.system.orgdata.entity.OrgData;
import cn.stylefeng.guns.modular.system.orgdata.exception.enums.OrgDataExceptionEnum;
import cn.stylefeng.guns.modular.system.orgdata.factory.OrgDataFactory;
import cn.stylefeng.guns.modular.system.orgdata.mapper.OrgDataMapper;
import cn.stylefeng.guns.modular.system.orgdata.pojo.request.CommonOrgDataTreeRequest;
import cn.stylefeng.guns.modular.system.orgdata.pojo.request.OrgDataRequest;
import cn.stylefeng.guns.modular.system.orgdata.pojo.response.CommonOrgDataTreeResponse;
import cn.stylefeng.guns.modular.system.orgdata.service.OrgDataService;
import cn.stylefeng.roses.kernel.cache.api.CacheOperatorApi;
import cn.stylefeng.roses.kernel.db.api.context.DbOperatorContext;
import cn.stylefeng.roses.kernel.db.api.factory.PageFactory;
import cn.stylefeng.roses.kernel.db.api.factory.PageResultFactory;
import cn.stylefeng.roses.kernel.db.api.pojo.entity.BaseEntity;
import cn.stylefeng.roses.kernel.db.api.pojo.page.PageResult;
import cn.stylefeng.roses.kernel.event.sdk.publish.BusinessEventPublisher;
import cn.stylefeng.roses.kernel.log.api.util.BusinessLogUtil;
import cn.stylefeng.roses.kernel.rule.constants.TreeConstants;
import cn.stylefeng.roses.kernel.rule.exception.base.ServiceException;
import cn.stylefeng.roses.kernel.rule.pojo.dict.SimpleDict;
import cn.stylefeng.roses.kernel.rule.tree.factory.DefaultTreeBuildFactory;
import cn.stylefeng.roses.kernel.sys.api.constants.SysConstants;
import cn.stylefeng.roses.kernel.sys.api.enums.org.DetectModeEnum;
import cn.stylefeng.roses.kernel.sys.api.pojo.org.CompanyDeptDTO;
import cn.stylefeng.roses.kernel.sys.modular.org.constants.OrgConstants;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.*;
import java.util.concurrent.ConcurrentHashMap;
import java.util.stream.Collectors;
import static java.util.stream.Collectors.toCollection;

/**
 * 组织机构信息业务实现层
 *
 * @author fengshuonan
 * @date 2023/06/10 21:23
 */
@Service
public class OrgDataServiceImpl extends ServiceImpl<OrgDataMapper, OrgData> implements OrgDataService {

/*    @Resource
    private SysUserService sysUserService;

    @Resource
    private HrPositionService hrPositionService;

    @Resource
    private SysUserOrgService sysUserOrgService;*/
    @Resource
    private UserOrgDataMapper userOrgDataMapper;

    @Resource
    private OrgDataMapper orgDataMapper;

    @Resource(name = "sysOrgSubFlagCache")
    private CacheOperatorApi<Boolean> sysOrgSubFlagCache;

    @Override
    public void add(OrgDataRequest orgdataRequest) {
        OrgData orgdata = new OrgData();
        BeanUtil.copyProperties(orgdataRequest, orgdata);

        // 填充父级parentIds
        OrgDataFactory.fillParentIds(orgdata);
        OrgDataFactory.fillParentIds(orgdata);

        this.save(orgdata);

        // 发布一个新增组织机构的事件
        BusinessEventPublisher.publishEvent(OrgDataConstants.ADD_ORGDATA_EVENT, orgdata);

        // 记录日志
        BusinessLogUtil.setLogTitle("添加数据机构，机构名称：" + orgdataRequest.getOrgName());
        BusinessLogUtil.addContent("新增的数据机构详情如下：\n", orgdata);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void del(OrgDataRequest orgdataRequest) {

        // 查询被删除组织机构的所有子级节点
        Set<Long> totalOrgIdSet = DbOperatorContext.me()
                .findSubListByParentId("sys_hr_orgdata", "org_pids", "org_id", orgdataRequest.getOrgId());
        totalOrgIdSet.add(orgdataRequest.getOrgId());

        // 执行删除操作
        this.baseDelete(totalOrgIdSet);

        // 发布删除机构的事件
        BusinessEventPublisher.publishEvent(OrgDataConstants.DELETE_ORGDATA_EVENT, null);

        // 记录日志
        BusinessLogUtil.setLogTitle("删除数据机构，数据机构ID：" + orgdataRequest.getOrgId());
        BusinessLogUtil.addContent("删除数据机构，数据机构ID：", orgdataRequest.getOrgId());
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void batchDelete(OrgDataRequest orgdataRequest) {

        Set<Long> orgIdList = orgdataRequest.getOrgIdList();

        // 批量查询组织机构下的下属机构
        for (Long orgId : orgIdList) {
            // 查询被删除组织机构的所有子级节点
            Set<Long> tempSubOrgIdList = DbOperatorContext.me().findSubListByParentId("orgdata", "org_pids", "org_id", orgId);
            orgIdList.addAll(tempSubOrgIdList);
        }

        // 执行删除操作
        this.baseDelete(orgIdList);

        // 发布删除机构的事件
        BusinessEventPublisher.publishEvent(OrgDataConstants.DELETE_ORGDATA_EVENT, null);

        // 记录日志
        BusinessLogUtil.setLogTitle("批量删除数据机构");
        BusinessLogUtil.addContent("批量删除数据机构，id集合为：", orgIdList);
    }

    @Override
    public void edit(OrgDataRequest orgdataRequest) {
        OrgData orgdata = this.queryOrgdata(orgdataRequest);

        BusinessLogUtil.setLogTitle("更新机构信息，机构名称为：", orgdata.getOrgName());
        BusinessLogUtil.addContent("更新前的机构信息为：\n", orgdata);

        BeanUtil.copyProperties(orgdataRequest, orgdata);

        // 填充父级parentIds
        OrgDataFactory.fillParentIds(orgdata);

        this.updateById(orgdata);

        // 发布编辑机构事件
        BusinessEventPublisher.publishEvent(OrgDataConstants.EDIT_ORGDATA_EVENT, null);

        // 记录日志
        BusinessLogUtil.addContent("更新后的机构信息为：\n", orgdata);

    }

    @Override
    public OrgData detail(OrgDataRequest orgdataRequest) {

        LambdaQueryWrapper<OrgData> wrapper = new LambdaQueryWrapper<>();

        wrapper.eq(OrgData::getOrgId, orgdataRequest.getOrgId());
        wrapper.select(OrgData::getOrgId, OrgData::getOrgName, OrgData::getOrgShortName, OrgData::getOrgCode,
                OrgData::getOrgParentId, OrgData::getOrgSort, OrgData::getStatusFlag,
                OrgData::getOrgPids);

        OrgData Orgdata = this.getOne(wrapper, false);
        if (ObjectUtil.isEmpty(Orgdata)) {
            throw new ServiceException(OrgDataExceptionEnum.HR_ORGANIZATION_NOT_EXISTED);
        }

        // 获取机构的上级机构名称
        String parentOrgName = this.getOrgNameById(Orgdata.getOrgParentId());
        Orgdata.setParentOrgName(parentOrgName);

        return Orgdata;
    }

    @Override
    public List<OrgData> findList(OrgDataRequest OrgdataRequest) {
        LambdaQueryWrapper<OrgData> wrapper = this.createWrapper(OrgdataRequest);
        return this.list(wrapper);
    }

    @Override
    public PageResult<OrgData> findPage(OrgDataRequest OrgdataRequest) {
        LambdaQueryWrapper<OrgData> wrapper = createWrapper(OrgdataRequest);

        // 只查询需要的字段
        wrapper.select(OrgData::getOrgId, OrgData::getOrgName, OrgData::getOrgCode, OrgData::getStatusFlag,
                OrgData::getOrgSort, BaseEntity::getCreateTime);

        Page<OrgData> sysRolePage = this.page(PageFactory.defaultPage(), wrapper);
        return PageResultFactory.createPageResult(sysRolePage);
    }

    @Override
    public PageResult<OrgData> commonOrgPage(OrgDataRequest OrgdataRequest) {

        LambdaQueryWrapper<OrgData> wrapper = createWrapper(OrgdataRequest);

        // 只查询需要的字段
        wrapper.select(OrgData::getOrgId, OrgData::getOrgName, OrgData::getOrgCode,
                OrgData::getStatusFlag, OrgData::getOrgParentId);

        Page<OrgData> sysRolePage = this.page(PageFactory.defaultPage(), wrapper);

        // 将每个机构的公司名称返回
        for (OrgData Orgdata : sysRolePage.getRecords()) {
            CompanyDeptDTO companyInfo = this.getOrgCompanyInfo(Orgdata);
            if (companyInfo == null) {
                continue;
            }
            Orgdata.setCompanyName(companyInfo.getCompanyName());
        }

        return PageResultFactory.createPageResult(sysRolePage);
    }

    @Override
    public CommonOrgDataTreeResponse commonOrgdataTree(CommonOrgDataTreeRequest commonOrgdataTreeRequest) {

        // 如果查询带组织机构名称的搜索，则清空其他条件
        if (ObjectUtil.isNotEmpty(commonOrgdataTreeRequest.getSearchText())) {
            commonOrgdataTreeRequest.setOrgParentId(null);
            commonOrgdataTreeRequest.setIndexOrgIdList(null);
        }

        // 如果查询待组织机构的状态信息，则清空parentId
        if (ObjectUtil.isNotEmpty(commonOrgdataTreeRequest.getIndexOrgIdList())) {
            commonOrgdataTreeRequest.setOrgParentId(null);
        }

        // 根据条件查询组织机构列表
        LambdaQueryWrapper<OrgData> wrapper = this.createCommonTreeWrapper(commonOrgdataTreeRequest);
        wrapper.select(OrgData::getOrgId, OrgData::getOrgPids, OrgData::getOrgParentId, OrgData::getOrgName,
                OrgData::getOrgSort);
        List<OrgData> orgDataList = this.list(wrapper);

        if (ObjectUtil.isEmpty(orgDataList)) {
            return new CommonOrgDataTreeResponse(orgDataList, new ArrayList<>());
        }

        // 如果查询条件不为空，则把相关的查询结果的父级也查询出来，组成一颗完整树
        String searchText = commonOrgdataTreeRequest.getSearchText();
        List<OrgData> parentOrgList = new ArrayList<>();
        if (ObjectUtil.isNotEmpty(searchText)) {
            Set<Long> orgParentIdList = OrgDataFactory.getOrgdataParentIdList(orgDataList);
            LambdaQueryWrapper<OrgData> parentWrapper = new LambdaQueryWrapper<>();
            parentWrapper.in(OrgData::getOrgId, orgParentIdList);
            parentOrgList = this.list(parentWrapper);
        }

        // 合并两个集合
        orgDataList.addAll(parentOrgList);

        // 去重
        List<OrgData> newNotRepeatList = orgDataList.stream().collect(
                Collectors.collectingAndThen(toCollection(() -> new TreeSet<>(Comparator.comparing(OrgData::getOrgId))),
                        LinkedList::new));

        // 从新排序，根据sort字段排序
        newNotRepeatList.sort(Comparator.comparing(OrgData::getOrgSort));

        // 构建树形结构
        if (ObjectUtil.isNotEmpty(commonOrgdataTreeRequest.getSearchText()) || ObjectUtil.isNotEmpty(
                commonOrgdataTreeRequest.getIndexOrgIdList())) {
            newNotRepeatList = new DefaultTreeBuildFactory<OrgData>().doTreeBuild(newNotRepeatList);
        }

        // 遍历所有节点，查询这些节点有没有子级，填充haveSubOrgFlag
        this.fillHaveSubFlag(newNotRepeatList);

        // 遍历这些节点，如果有children的，都展开，并搜集到数组里
        List<Long> expandOrgIds = new ArrayList<>();
        this.fillExpandFlag(newNotRepeatList, expandOrgIds);

        return new CommonOrgDataTreeResponse(newNotRepeatList, expandOrgIds);
    }

    @Override
    public CompanyDeptDTO getCompanyDeptInfo(Long orgId) {

        if (orgId == null) {
            return null;
        }

        OrgData Orgdata = this.getById(orgId);
        if (Orgdata == null) {
            return null;
        }

        // 获取当前组织机构id是公司还是部门，如果是公司，则直接返回结果
//        if (OrgTypeEnum.COMPANY.getCode().equals(OrgData.getOrgType())) {
//            return new CompanyDeptDTO(OrgData.getOrgId(), OrgData.getOrgName());
//        }

        // 如果是部门，则递归向上查询到部门所属的公司id
        CompanyDeptDTO orgCompanyInfo = this.getOrgCompanyInfo(Orgdata);

        // 查到公司id之后，设置部门id则为参数orgId
        if (orgCompanyInfo != null) {
            orgCompanyInfo.setDeptId(Orgdata.getOrgId());
            orgCompanyInfo.setDeptName(Orgdata.getOrgName());
        }

        return orgCompanyInfo;
    }

    @Override
    public CompanyDeptDTO getOrgCompanyInfo(OrgData Orgdata) {

        if (Orgdata == null) {
            return null;
        }

        // 如果是到了根节点，则直接返回当前根节点信息
        if (TreeConstants.DEFAULT_PARENT_ID.equals(Orgdata.getOrgParentId())) {
            return new CompanyDeptDTO(Orgdata.getOrgId(), Orgdata.getOrgName());
        }

        // 如果当前已经是公司类型，则直接返回
//        if (OrgTypeEnum.COMPANY.getCode().equals(OrgData.getOrgType())) {
//            return new CompanyDeptDTO(OrgData.getOrgId(), OrgData.getOrgName());
//        }

        // 查询父级是否是公司
        Long orgParentId = Orgdata.getOrgParentId();
        OrgData parentOrgInfo = this.getById(orgParentId);
        return this.getOrgCompanyInfo(parentOrgInfo);
    }

    @Override
    public CompanyDeptDTO getOrgCompanyInfo(Long orgId) {

        if (orgId == null) {
            return null;
        }

        // 查询组织机构对应的信息
        LambdaQueryWrapper<OrgData> OrgdataLambdaQueryWrapper = new LambdaQueryWrapper<>();
        OrgdataLambdaQueryWrapper.eq(OrgData::getOrgId, orgId);
        OrgdataLambdaQueryWrapper.select(OrgData::getOrgId, OrgData::getOrgParentId);
        OrgData Orgdata = this.getOne(OrgdataLambdaQueryWrapper, false);

        if (Orgdata == null) {
            return null;
        }

        // 查询机构对应的公司部门信息
        return this.getOrgCompanyInfo(Orgdata);
    }

    /*@Override
    public HomeCompanyInfo orgStatInfo() {

        // todo 加缓存

        HomeCompanyInfo homeCompanyInfo = new HomeCompanyInfo();

        // 1. 总机构数量
        long totalOrgCount = this.count();
        homeCompanyInfo.setOrganizationNum(totalOrgCount);

        // 2. 总人员数量
        long totalUserCount = sysUserService.count();
        homeCompanyInfo.setEnterprisePersonNum(totalUserCount);

        // 3. 总职位信息
        long totalPositionCount = hrPositionService.count();
        homeCompanyInfo.setPositionNum(totalPositionCount);

        // 4. 当前公司下的机构数量
        Long currentOrgId = LoginContext.me().getLoginUser().getCurrentOrgId();
        CompanyDeptDTO orgCompanyInfo = this.getOrgCompanyInfo(currentOrgId);

        // 当前用户没公司，则直接设置为0
        if (currentOrgId == null || orgCompanyInfo == null) {
            homeCompanyInfo.setCurrentCompanyPersonNum(0L);
            homeCompanyInfo.setCurrentCompanyPersonNum(0L);
            return homeCompanyInfo;
        }

        Long companyId = orgCompanyInfo.getCompanyId();

        // 获取当前公司的所有子公司数量(含当前公司)
        LambdaQueryWrapper<OrgData> wrapper = Wrappers.lambdaQuery(OrgData.class)
                .like(OrgData::getOrgPids, LEFT_SQUARE_BRACKETS + companyId + RIGHT_SQUARE_BRACKETS).or()
                .eq(OrgData::getOrgId, companyId).select(OrgData::getOrgId);
        List<OrgData> organizations = this.list(wrapper);
        homeCompanyInfo.setCurrentDeptNum(organizations.size());

        // 5. 当前机构下的人员数量
        if (ObjectUtil.isEmpty(organizations)) {
            homeCompanyInfo.setCurrentCompanyPersonNum(0L);
        } else {
            List<Long> orgIdList = organizations.stream().map(OrgData::getOrgId).collect(Collectors.toList());
            LambdaQueryWrapper<SysUserOrg> userWrapper = new LambdaQueryWrapper<SysUserOrg>().in(SysUserOrg::getOrgId, orgIdList);
            userWrapper.select(SysUserOrg::getUserId);
            List<SysUserOrg> list = sysUserOrgService.list(userWrapper);
            Set<Long> currentOrgUserSize = list.stream().map(SysUserOrg::getUserId).collect(Collectors.toSet());
            homeCompanyInfo.setCurrentCompanyPersonNum(Convert.toLong(currentOrgUserSize.size()));
        }

        return homeCompanyInfo;
    }
*/
    @Override
    public Set<Long> queryOrgIdParentIdList(Set<Long> orgIdList) {

        Set<Long> parentIdListTotal = new HashSet<>();

        if (ObjectUtil.isEmpty(orgIdList)) {
            return parentIdListTotal;
        }

        // 首先加上参数的机构集合
        parentIdListTotal.addAll(orgIdList);

        LambdaQueryWrapper<OrgData> OrgdataLambdaQueryWrapper = new LambdaQueryWrapper<>();
        OrgdataLambdaQueryWrapper.in(OrgData::getOrgId, orgIdList);
        OrgdataLambdaQueryWrapper.select(OrgData::getOrgPids);
        List<OrgData> orgDataList = this.list(OrgdataLambdaQueryWrapper);

        for (OrgData Orgdata : orgDataList) {
            String orgPids = Orgdata.getOrgPids();
            if (ObjectUtil.isEmpty(orgPids)) {
                continue;
            }

            orgPids = orgPids.replaceAll("\\[", "");
            orgPids = orgPids.replaceAll("]", "");

            String[] split = orgPids.split(",");
            for (String pidString : split) {
                parentIdListTotal.add(Convert.toLong(pidString));
            }
        }

        return parentIdListTotal;
    }

    @Override
    public Boolean getOrgdataHaveSubFlag(Long orgId) {

        if (ObjectUtil.isEmpty(orgId)) {
            return false;
        }

        Boolean cacheResult = sysOrgSubFlagCache.get(orgId.toString());
        if (cacheResult != null) {
            return cacheResult;
        }

        // 查询库中是否有上级包含了本orgId
        LambdaQueryWrapper<OrgData> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(OrgData::getOrgParentId, orgId);
        wrapper.select(OrgData::getOrgId);
        List<OrgData> orgDataList = this.list(wrapper);

        // 查询结果加到缓存中
        if (orgDataList.size() > 0) {
            // 过期时间3600秒
            sysOrgSubFlagCache.put(orgId.toString(), true, SysConstants.DEFAULT_SYS_CACHE_TIMEOUT_SECONDS);
            return true;
        } else {
            // 过期时间3600秒
            sysOrgSubFlagCache.put(orgId.toString(), false, SysConstants.DEFAULT_SYS_CACHE_TIMEOUT_SECONDS);
            return false;
        }
    }

    @Override
    public List<SimpleDict> getOrgListName(OrgDataRequest OrgdataRequest) {

        List<SimpleDict> dictList = new ArrayList<>();

        if (ObjectUtil.isEmpty(OrgdataRequest) || ObjectUtil.isEmpty(OrgdataRequest.getOrgIdList())) {
            return dictList;
        }

        LambdaQueryWrapper<OrgData> wrapper = new LambdaQueryWrapper<>();
        wrapper.in(OrgData::getOrgId, OrgdataRequest.getOrgIdList());
        wrapper.select(OrgData::getOrgName, OrgData::getOrgId, OrgData::getOrgCode);
        List<OrgData> list = this.list(wrapper);

        if (ObjectUtil.isEmpty(list)) {
            return dictList;
        }

        for (OrgData Orgdata : list) {
            dictList.add(new SimpleDict(Orgdata.getOrgId(), Orgdata.getOrgName(), Orgdata.getOrgCode()));
        }

        return dictList;
    }

    @Override
    public String getOrgNameById(Long orgId) {

        if (TreeConstants.DEFAULT_PARENT_ID.equals(orgId)) {
            return OrgConstants.NONE_PARENT_ORG;
        }

        if (ObjectUtil.isEmpty(orgId)) {
            return OrgConstants.NONE_PARENT_ORG;
        }

        LambdaQueryWrapper<OrgData> OrgdataLambdaQueryWrapper = new LambdaQueryWrapper<>();
        OrgdataLambdaQueryWrapper.eq(OrgData::getOrgId, orgId);
        OrgdataLambdaQueryWrapper.select(OrgData::getOrgName);
        OrgData one = this.getOne(OrgdataLambdaQueryWrapper);

        if (one != null) {
            return one.getOrgName();
        }

        return OrgConstants.NONE_PARENT_ORG;
    }

    @Override
    public Long getParentLevelOrgId(Long orgId, Integer parentLevelNum, DetectModeEnum detectModeEnum) {
        if (DetectModeEnum.TO_TOP.equals(detectModeEnum)) {
            return calcParentOrgId(orgId, parentLevelNum, true);
        } else {
            return calcParentOrgId(orgId, parentLevelNum, false);
        }
    }

    @Override
    public CompanyDeptDTO remoteGetOrgCompanyDept(Long orgId) {
        return this.getOrgCompanyInfo(orgId);
    }

    /**
     * 获取信息
     *
     * @author fengshuonan
     * @date 2023/06/10 21:23
     */
    private OrgData queryOrgdata(OrgDataRequest OrgdataRequest) {
        OrgData Orgdata = this.getById(OrgdataRequest.getOrgId());
        if (ObjectUtil.isEmpty(Orgdata)) {
            throw new ServiceException(OrgDataExceptionEnum.HR_ORGANIZATION_NOT_EXISTED);
        }
        return Orgdata;
    }

    /**
     * 创建查询wrapper
     *
     * @author fengshuonan
     * @date 2023/06/10 21:23
     */
    private LambdaQueryWrapper<OrgData> createWrapper(OrgDataRequest OrgdataRequest) {
        LambdaQueryWrapper<OrgData> queryWrapper = new LambdaQueryWrapper<>();

        // 如果按文本查询条件不为空，则判断组织机构名称、简称是否有匹配
        String searchText = OrgdataRequest.getSearchText();
        if (StrUtil.isNotEmpty(searchText)) {
            queryWrapper.nested(wrap -> {
                wrap.like(OrgData::getOrgName, searchText);
                wrap.or().like(OrgData::getOrgShortName, searchText);
                wrap.or().like(OrgData::getOrgCode, searchText);
            });
        }

        // 根据机构状态查询
        Integer statusFlag = OrgdataRequest.getStatusFlag();
        queryWrapper.eq(ObjectUtil.isNotNull(statusFlag), OrgData::getStatusFlag, statusFlag);

        // 如果查询条件有orgId，则查询指定机构下的子机构
        Long orgId = OrgdataRequest.getOrgId();
        if (orgId != null) {
            // 查询orgId对应的所有子机构，包含本orgId
            queryWrapper.nested(wrap -> {
                wrap.eq(OrgData::getOrgParentId, orgId).or().eq(OrgData::getOrgId, orgId);
            });
        }

        // 根据排序正序查询
        queryWrapper.orderByAsc(OrgData::getOrgSort);

        return queryWrapper;
    }

    /**
     * 批量删除组织机构
     *
     * @author fengshuonan
     * @since 2023/6/11 17:00
     */
    private void baseDelete(Set<Long> totalOrgIdSet) {
        Map<String, Object> queryWrapper = new ConcurrentHashMap<String, Object>();
        queryWrapper.put("orgIdlist", totalOrgIdSet);
        //判断该数据机构下是否有人员，有则报错不需删除
        Long userCount = userOrgDataMapper.getUserCountByOrgID(queryWrapper);
        if(userCount>0){
            throw new ServiceException(OrgDataExceptionEnum.DELETE_ORGANIZATION_ERROR);
        }
        //判断该数据机构下是否有订单，有则报错不需删除


        // 批量删除所有相关节点
        this.removeBatchByIds(totalOrgIdSet);
    }

    /**
     * 创建查询wrapper
     *
     * @author fengshuonan
     * @date 2023/06/10 21:23
     */
    private LambdaQueryWrapper<OrgData> createCommonTreeWrapper(CommonOrgDataTreeRequest commonOrgdataTreeRequest) {

        // 创建基本的wrapper
        OrgDataRequest OrgdataRequest = new OrgDataRequest();
        OrgdataRequest.setSearchText(commonOrgdataTreeRequest.getSearchText());
        LambdaQueryWrapper<OrgData> queryWrapper = this.createWrapper(OrgdataRequest);

        // 如果查询条件有orgId，则查询指定机构下的子机构
        Long parentId = commonOrgdataTreeRequest.getOrgParentId();
        if (parentId != null) {
            queryWrapper.eq(OrgData::getOrgParentId, parentId);
        }

        // 如果有定位状态的组织机构，则需要查询到定位的组织机构的所有子一级
        Set<Long> indexOrgIdList = commonOrgdataTreeRequest.getIndexOrgIdList();
        if (ObjectUtil.isNotEmpty(indexOrgIdList)) {
            Set<Long> parentIdListTotal = this.queryOrgIdParentIdList(indexOrgIdList);
            if (ObjectUtil.isNotEmpty(parentIdListTotal)) {
                queryWrapper.in(OrgData::getOrgParentId, parentIdListTotal);
            }
        }

        // 如果有筛选公司的标识，则只查询公司列表
//        Boolean companySearchFlag = commonOrgTreeRequest.getCompanySearchFlag();
//        if (ObjectUtil.isNotEmpty(companySearchFlag) && companySearchFlag) {
//            queryWrapper.eq(OrgData::getOrgType, OrgTypeEnum.COMPANY.getCode());
//        }

        return queryWrapper;
    }

    /**
     * 填充是否含有下级的标识
     *
     * @author fengshuonan
     * @since 2023/7/13 21:30
     */
    private void fillHaveSubFlag(List<OrgData> orgData) {

        if (ObjectUtil.isEmpty(orgData)) {
            return;
        }

        for (OrgData orgdata : orgData) {

            Long orgId = orgdata.getOrgId();

            // 查询是否包含下级，并设置标识
            Boolean orgdataHaveSubFlag = this.getOrgdataHaveSubFlag(orgId);
            orgdata.setHaveSubOrgdataFlag(orgdataHaveSubFlag);

            // 如果有children则将展开标识填充，并继续向下递归填充
            if (ObjectUtil.isNotEmpty(orgdata.getChildren())) {
                fillHaveSubFlag(orgdata.getChildren());
            }

        }

    }

    /**
     * 填充是否展开的标识
     * <p>
     * 判定是否展开，如果有children则展开
     *
     * @author fengshuonan
     * @since 2023/7/17 11:11
     */
    private void fillExpandFlag(List<OrgData> organizations, List<Long> expandOrgIds) {

        if (ObjectUtil.isEmpty(organizations)) {
            return;
        }

        for (OrgData organization : organizations) {

            Long orgId = organization.getOrgId();

            // 如果有children则将展开标识填充，并继续向下递归填充
            if (ObjectUtil.isNotEmpty(organization.getChildren())) {
                expandOrgIds.add(orgId);

                // 搜集子集的children的展开标识
                fillExpandFlag(organization.getChildren(), expandOrgIds);
            }
        }
    }

    /**
     * 计算获取上级组织机构id
     *
     * @param orgId          指定机构id
     * @param parentLevelNum 上级机构的层级数，从0开始，0代表不计算直接返回本身
     * @param reverse        是否反转，true-代表自下而上计算，false-代表自上而下计算
     * @author fengshuonan
     * @since 2022/10/1 11:45
     */
    private Long calcParentOrgId(Long orgId, Integer parentLevelNum, boolean reverse) {

        if (ObjectUtil.isEmpty(orgId) || ObjectUtil.isEmpty(parentLevelNum)) {
            return null;
        }

        // 如果上级层数为0，则直接返回参数的orgId，代表同级别组织机构
        if (parentLevelNum == 0) {
            return orgId;
        }

        // 获取当前部门的所有父级id
        OrgData Orgdata = this.getById(orgId);
        if (Orgdata == null || StrUtil.isEmpty(Orgdata.getOrgPids())) {
            return null;
        }
        String orgParentIdListStr = Orgdata.getOrgPids();

        // 去掉中括号符号
        orgParentIdListStr = orgParentIdListStr.replaceAll("\\[", "");
        orgParentIdListStr = orgParentIdListStr.replaceAll("]", "");

        // 获取所有上级id列表
        String[] orgParentIdList = orgParentIdListStr.split(",");
        if (reverse) {
            orgParentIdList = ArrayUtil.reverse(orgParentIdList);
        }

        // 先删掉id为-1的机构，因为-1是不存在的
        ArrayList<String> parentOrgIdList = new ArrayList<>();
        for (String orgIdItem : orgParentIdList) {
            if (!TreeConstants.DEFAULT_PARENT_ID.toString().equals(orgIdItem)) {
                parentOrgIdList.add(orgIdItem);
            }
        }

        // 根据请求参数，需要从parentOrgIdList获取的下标
        int needGetArrayIndex = parentLevelNum - 1;

        // parentOrgIdList最大能提供的下标
        int maxCanGetIndex = parentOrgIdList.size() - 1;

        // 如果没有最顶级的上级，则他本身就是最顶级上级
        if (maxCanGetIndex < 0) {
            return orgId;
        }

        // 根据参数传参，进行获取上级的操作
        String orgIdString;
        if (needGetArrayIndex <= (maxCanGetIndex)) {
            orgIdString = parentOrgIdList.get(needGetArrayIndex);
        } else {
            // 如果需要获取的下标，大于了最大下标
            if (reverse) {
                orgIdString = parentOrgIdList.get(maxCanGetIndex);
            } else {
                return orgId;
            }
        }
        return Long.valueOf(orgIdString);
    }

}